var express = require("express");
var expressWs = require("express-ws");

var app = express.Router();
expressWs(app);  // 将 WebSocket 服务混入 app，相当于为 app 添加 .ws 方法

var share = require("../share");

express.wsClients = linkkey_Clients_ws;

app.ws("/wb", function (ws, req) {
  //console.log("新链接", ws, req);
  let link_key = share.linksuccess(ws, req);
  ws.on("message", function (msg) {
    let info = linkkey_Clients_ws[link_key]
    //console.log("\n接收:", info.dataType, msg.length, msg);   

    if(msg == "1")
    { //心跳
      ws.send(msg);
      return;
    }

    try {
      var data = JSON.parse(msg);
      if (data != null) {
        let cmd =data.c;
        let cmdarr = cmd.split(".");
        if (cmdarr.length == 2) {
          let code = require(`./sockets/net_${cmdarr[0]}`)
          if (cmd == "user.login") {
            code.login(link_key, ws, data, msg)
          }
          else {
            var id = linkkey_Clients_id[link_key]
           // console.log("查找接口:",cmd,id,link_key)
            if(id!=null)
            {
             // console.log("接口找到:",cmd,cmdarr[1],code,id,ws._isServer)
              eval(`code.${cmdarr[1]}(id,data, msg)`)
            }
            else
            {
              share.send_response_by_ws(ws,"error",{code:401,msg:"please log in first"});
            }
          }
        }
      }
    } catch (err) {
      console.log(err)
      share.send_response_by_ws(ws,"error",{code:402,msg:err.message});
    }
  },
    // close 事件表示客户端断开连接时执行的回调函数
    ws.on('close', function (e) {
      console.log("close link")
      share.closeLink(link_key)
    }),
  );
})

module.exports = app;